var MailFolder = Class.create();
MailFolder.prototype = {
	initialize : function() {
                         this.last_param = null;
                         this.re_requet = false;
                         this.isInit = false;
                     },
        initEvent: function(){
                    var update_notifier = false;
                    var update_pop = false;
                    for(var i in mailPop.PopAccounts){
                        if(mailPop.PopAccounts[i]){
                            update_pop = true;
                            break;
                        }
                    }
                    for (var i = 0; i < FolderList.length; i++) {
                        if(FolderList[i].folder_id > 16){
                            update_notifier = true;
                            break;
                        }
                    }
                    for (var i = 0; i < FolderList.length; i++) {
                        FoldersData.password = false;
                        if(FolderList[i].password == true){
                            FoldersData.password = true;
                            break;
                        }
                    }
                    if(!this.isInit){
                        var s = [
                        {'name' : 's_folderlock', exec : function(){changePanel('folderLock')}},
                        {'name' : 's_popfolderlock', exec : function(){changePanel('folderLock')}}
                        ];
                        Event.observe(DOM.left, 'click', function(event){
                                var EL = event.target;
                                s.each(function(item){
                                    try {
                                    var e = Element.getParentNodeByClassName(EL, item.name);
                                    if (e) {
                                    try {
                                    item.exec();
                                    } catch (e) {}
                                    Event.stop(event);
                                    return false;
                                    }
                                    } catch(e) {}
                                    }
                                    );
                                });
                        this.isInit = true;
                    }
                    if(update_pop){
                        var EL = document.getElementsByClassName('s_daishoucreate')[0];
                        Element.setStyle(EL, {'display' : 'none'});
                        EL = document.getElementsByClassName('s_popfolderlock')[0];
                        Element.setStyle(EL, {'display' : ''});
                    }
                    else{
                        var EL = document.getElementsByClassName('s_daishoucreate')[0];
                        Element.setStyle(EL, {'display' : ''});
                        EL = document.getElementsByClassName('s_popfolderlock')[0];
                        Element.setStyle(EL, {'display' : 'none'});
                    }
                    if(update_notifier){
                        var EL = document.getElementsByClassName('s_foldercreate')[0];
                        Element.setStyle(EL, {'display' : 'none'});
                        EL = document.getElementsByClassName('s_folderlock')[0];
                        Element.setStyle(EL, {'display' : ''});
                    }
                    else{
                        var EL = document.getElementsByClassName('s_foldercreate')[0];
                        Element.setStyle(EL, {'display' : ''});
                        EL = document.getElementsByClassName('s_folderlock')[0];
                        Element.setStyle(EL, {'display' : 'none'});
                    }
                   },
        cancel_update : function(){
                                         Element.setStyle($('changearea'), {'display' : 'none'});
                        },
        prelock : function(event){
                      try{
                      }catch(e){
                      }
                  },
        getBindStatusCallBack: function(ret){
                                    if(ret.status == 0){
                                        hiddenAllPanel();
                                        var tem = new Template(FoloderLockerOptionTemplate);
                                        var data = new Object();
                                        $('mailConfiguration').innerHTML = tem.evaluate(data);
                                        $('mailConfiguration').show();
                                        return false;
                                    }
                                    else if(ret.status == 1){
                                        hiddenAllPanel();
                                        var tem = new Template(FoloderLockerPasswordTemplate);
                                        var data = new Object();
                                        this.cell_num = ret.mobile;
                                        var may_numb = this.cell_num.substring(0, 3) + "****" + this.cell_num.substring(7, 11);
                                        data.CellNumber = may_numb;
                                        $('mailConfiguration').innerHTML = tem.evaluate(data);
                                        $('mailConfiguration').show();
                                        return false;
                                    }
                                    else{
                                        // 这里应当直接退出,因为后端说,没有
                                        // header...
                                        changePanel('mainPage');
                                    }
                                   },
        getBindStatus : function(){
                            },
        valid_password: function(){
                            var _p_n = this.cell_num;
                            var _p_w = $('p_password').value;
                            try{
                                var para = {'phone_number' : _p_n, 'password' : hex_md5(_p_w)}
                                _defun('http://mail.sohu.com/papp/json_interface/check_binding_status.jsp?' + Math.round(Math.random()*10000) + Math.round(Math.random()*10000), 'post', para, this.valid_passwordCallBack.bind(this));
                            }catch(e){
                            }
                        },
        initOperationPage : function(){
                                        hiddenAllPanel();
                                        var tem = new Template(FoloderOperationTemplate);
                                        var data = new Object();
                                        var folder_list_str = '';
                                        var data_buf = [];
                                        try{
                                        for (var i = 0; i < FolderList.length; i++) {
                                            if(FolderList[i].folder_id > 16){
                                                folder_list_str += ['<dd style="margin-left:5px;">', '<input type="checkbox" style="vertical-align:middle;" checked class="lock_folder" folder_id="', FolderList[i].folder_id, '" />', FolderList[i].name, '</dd>'].join("");

                                            }
                                        }
                                        }
                                        catch(e){
                                        }
                                        data['folder_lists'] = folder_list_str;
                                        $('mailConfiguration').innerHTML = tem.evaluate(data);
                                        $('mailConfiguration').show();
                                        return false;
                            },
        set_password : function(){
                           var _pass = $('lock_pass').value;
                           var _vpass = $('r_lock_pass').value;
                           var msg = '';
                           if(_pass != _vpass){
                               msg = '两次输入的密码不统一，请重新输入！';
                               _dialog.alert({'info' : msg});
                               return;
                           }
                           var _re = /\w{6,16}/;
                           if(!_re.test(_pass)){
                               msg = '密码必须是6-16位的数字或者英文字母。';
                               _dialog.alert({'info' : msg});
                               return;
                           }
                           var folder_ids = document.getElementsByClassName('lock_folder');
                           var idlist = new Array();
                           for(var i = 0; i < folder_ids.length; i++){
                                if(folder_ids[i].checked == true){
                                   idlist.push(folder_ids[i].getAttribute('folder_id'));
                                }
                           }
                           var para = {'password' : _pass, 'scode' : this.sec_code, folder_ids : idlist, 'act' : 'set'};
                           folder_lock(para, mailfolder.set_lock_success.bind(this));
                       },
        set_lock_success : function(ret){
                               if(ret.status){
                                   var fids = ret.msg;
                                   for (var j = 0; j < FolderList.length; j++) {
                                           if(FolderList[j].folder_id > 16){
                                               FolderList[j].password = false;
                                           }
                                   }
                                   for(var i = 0; i < fids.length; i++){
                                        for (var j = 0; j < FolderList.length; j++) {
                                            if(FolderList[j].folder_id > 16 && FolderList[j].folder_id == fids[i]){
                                                FolderList[j].password = true;
                                            }
                                        }
                                   }
                                   this.initEvent();
                                   FoldersData.password = true;
                                   mailCfgClass.cfgSuccPrompt = true;
                                   mailCfgClass.initMailCfg();
                               }else{
                                   _dialog.alert({'info' : ret.msg});
                               }
                           },

        valid_passwordCallBack : function(ret){
                                     // 因为接口broken, 这里先搞一个正确的
                                     var msg = '';
                                     if(ret.status == 0){
                                         this.sec_code = ret.scode;
                                         // 接下来是漂亮的选择页面吧
                                         this.initOperationPage();
                                         return false;
                                     }
                                     else if(ret.status == 1){
                                         msg = "密码错，请重新输入。";
                                     }
                                     else if(ret.status == 2){
                                         msg = "绑定关系出错。";
                                     }
                                     else if(ret.status == -1){
                                         msg = "请确认登录状态。";
                                     }
                                     else{
                                         msg = "系统错误，请稍后重试。";
                                     }
                                     _dialog.alert({'info' : msg});
                                     return false;
                                 },
        initUI : function(){
                     jsoplog.ucCapture('folderlock');
                     if(FoldersData.password){
                         this.checkPassword(
                                 function(){
                                    mailfolder.initMangePage();
                                 }
                                 );
                     }
                     else{
                         // 检查绑定状态
                         _defun('http://mail.sohu.com/papp/json_interface/get_binding_status.jsp?' + Math.round(Math.random()*10000) + Math.round(Math.random()*10000), 'get', {}, this.getBindStatusCallBack.bind(this))
                     }
                 },
        initMangePage: function(){
                                        hiddenAllPanel();
                                        var tem = new Template(FolderLockManger);
                                        var data = new Object();
                                        var folder_list_str = '';
                                        var data_buf = [];
                                        try{
                                        for (var i = 0; i < FolderList.length; i++) {
                                            if(FolderList[i].folder_id > 16){
                                                if(FolderList[i].password == true)
                                                    folder_list_str += ['<dd style="margin-left:5px;">', '<input type="checkbox" checked class="lock_folder"  style="vertical-align:middle;" folder_id="', FolderList[i].folder_id, '" />', FolderList[i].name, '</dd>'].join("");
                                                else
                                                    folder_list_str += ['<dd style="margin-left:5px;">', '<input type="checkbox" class="lock_folder" style="vertical-align:middle;" folder_id="', FolderList[i].folder_id, '" />', FolderList[i].name, '</dd>'].join("");
                                            }
                                        }
                                        }
                                        catch(e){
                                        }
                                        data['folder_lists'] = folder_list_str;
                                        $('mailConfiguration').innerHTML = tem.evaluate(data);
                                        $('mailConfiguration').show();
                                        return false;
                       },
        checkPassword : function(callback, id){
                                this.check_callback = callback;
                                var fid = 0;
                                if(typeof(id) == "number" || typeof(id) == "string"){
                                    fid = id;
//                                    var para = {'act' : 'valid', 'fid' : id};
//                                    folder_lock(para, mailfolder.valid_success.bind(this));
                                }
                                var para = {'act' : 'valid', 'fid' : fid};
                                folder_lock(para, mailfolder.valid_success.bind(this));
//                                else{
//                                    var para = {'act' : 'valid', 'fid' : 0};
//                                    folder_lock(para, mailfolder.valid_success.bind(this));
////                                    hiddenAllPanel();
////                                    var tem = new Template(OpenFolderLock);
////                                    var data = new Object();
////                                    $('mailConfiguration').innerHTML = tem.evaluate(data);
////                                    $('mailConfiguration').show();
//                                }
                        },
        clear_password: function(){
                            hiddenAllPanel();
                            var tem = new Template(ClearLockManger);
                            var data = new Object();
                            $('mailConfiguration').innerHTML = tem.evaluate(data);
                            $('mailConfiguration').show();

                },
        clear_password_action: function(){
                           var _pass = $('clear_valid_password').value;
                           var _re = /^\w{6,16}$/;
                           if(!_re.test(_pass)){
                               var msg = '密码必须是6-16位的数字或者英文字母。';
                               _dialog.alert({'info' : msg});
                               return;
                           }
                           var para = {'password' : _pass, 'act' : 'clear'};
                           folder_lock(para, mailfolder.clear_valid_success.bind(this));
                       },
        clear_valid_success : function(ret){
                                  var data = new Object();
                                  if(ret.status){
                                      FoldersData.password = false; 
                                      data['promt'] = '<dt>密码锁解除成功</dt><dd>感谢您使用搜狐邮箱密码锁功能。</dd>';
                                  }
                                  else{
                                      msg = ret.msg;
                                      _dialog.alert({'info' : msg});
                                      return;
                                  }
                                  hiddenAllPanel();
                                  var tem = new Template(ClearCompleTemplate);
                                  $('mailConfiguration').innerHTML = tem.evaluate(data);
                                  $('mailConfiguration').show();
                                  var s = function(){
                                      var m = setTimeout(function(){
                                              }, 500);
                                  }

                              },
        valid_success : function(ret){
                            if(ret.status && this.check_callback && typeof(this.check_callback) == 'function'){
                                    this.check_callback();
                            }
                            else{
                                hiddenAllPanel();
                                var tem = new Template(OpenFolderLock);
                                var data = new Object();
                                $('mailConfiguration').innerHTML = tem.evaluate(data);
                                $('mailConfiguration').show();
                            }
                        },
        check_success : function(ret){
                            if(!ret.status){
                                _dialog.alert({'info' : ret.msg});
                                return;
                            }
                            else{
                                if(this.check_callback && typeof(this.check_callback) == 'function'){
                                    this.check_callback();
                                }
                            }
                        },
        check_password : function(){
                             var para = {'password' : $('valid_pass').value, fid : [], 'act' : 'check'};
                             folder_lock(para, mailfolder.check_success.bind(this));
                         },
        /*
         * show_folder应当有三个返回值
         *  1.  0   --  没锁
         *  2.  1   --  应当显示锁标志(锁状态)
         *  3.  2   --  应当显示锁标志(开锁状态)
         *
         *  cookie的花名叫folder_lock, httponly属性
         * */
        show_folder: function(){
                         return FoldersData.password == false ? 0 : (mailcookie.getCookie('folder_lock') == null ? 1 : 2 );
                     },

        bind_cell: function(){
                       this.cell_num = $('phone_number').value;
                       _defun('http://mail.sohu.com/papp/json_interface/get_binding_token.jsp?' + Math.round(Math.random()*10000), 'post', {'phone_number' : this.cell_num}, this.getBindToken.bind(this));
                   },
        getBindToken: function(ret){
                       var may_numb = this.cell_num.substring(0, 3) + "****" + this.cell_num.substring(7, 11);
                       if(ret.status == 0){
                           var msg = "该手机号码已经与其他账号绑定！";
                           _dialog.alert({'info' : msg});
                           return false;
                       }
                       else{
                           $('cell_bind_btn').disabled = true;
                           $('cell_bind_notifier').innerHTML = "请用手机号码 " + may_numb + " 发送<font color='red'> " + ret.code + "</font> 到 <font color='red'>10666666701</font> (资费 0.1 元)<br />发送完毕,接到我们下发的确认短信后,请点此【<a href='javascript:;' onclick='mailfolder.initUI()'>刷新</a>】";
                       }
                      },
        update_password : function(){
                              var msg = '';
                              var _o_password = $('old_folder_pass').value;
                              var _n_password = $('new_folder_pass').value;
                              var _nv_password = $('reply_folder_pass').value;
                              if(_n_password == "" ||  _nv_password == "" || _o_password == ""){
                                msg = '密码不应为空，请重新设置！';
                                _dialog.alert({'info' : msg});
                                return;
                              }
                              if(_n_password != _nv_password){
                                msg = '两次输入的密码不统一，请重新输入！';
                                _dialog.alert({'info' : msg});
                                return;
                              }
                              var _re = /^\w{6,16}$/;
                              if(!_re.test(_n_password)){
                                  msg = '密码必须是6-16位的数字或者英文字母。';
                                  _dialog.alert({'info' : msg});
                                  return;
                              }
                              var param = {'password' : _o_password, 'npassword' : _n_password, 'act' : 'replace'};
                              folder_lock(param, mailfolder.update_password_success.bind(this));
                          },
        update_password_success: function(ret){
                                     if(ret.status){
                                        Element.setStyle($('changearea'), {'display' : 'none'});
                                        mailCfgClass.cfgSuccPrompt = true;
                                        mailCfgClass.initMailCfg();
                                     }
                                     else{
                                        _dialog.alert({'info' : ret.msg});
                                        return;
                                     }
                                 },
        update_folder_success : function(ret){
                                    if(ret.status){
                                        var fids = ret.msg;
                                        for (var j = 0; j < FolderList.length; j++) {
                                                if(FolderList[j].folder_id > 16){
                                                    FolderList[j].password = false;
                                                }
                                        }
                                        for(var i = 0; i < fids.length; i++){
                                             for (var j = 0; j < FolderList.length; j++) {
                                                if(FolderList[j].folder_id > 16 && FolderList[j].folder_id == fids[i]){
                                                    FolderList[j].password = true;
                                                }
                                            }
                                        }
                                        this.initEvent();
                                        _dialog.alert({'info': '文件夹选择保存成功！'});
                                    }
                                    else{
                                        _dialog.alert({'info': ret.msg});
                                    }
                        },
        f_get_status_success : function(ret){
                                   this.cell_num = '';
                                   if(ret.status == 1){
                                   this.cell_num = ret.mobile;
                                   var may_numb = this.cell_num.substring(0, 3) + "****" + this.cell_num.substring(7, 11);
                                   hiddenAllPanel();
                                   var tem = new Template(FolderLockForget);
                                   var data = new Object();
                                   data['cell_number'] = may_numb;
                                   $('mailConfiguration').innerHTML = tem.evaluate(data);
                                   $('mailConfiguration').show();
                                   }
                                   else{
                                       changePanel('mainPage');
                                   }
                               },
        change_password: function(){
                             Element.setStyle($('changearea'), {'display' : ''});
                         },
        forget_password : function(){
                            _defun('http://mail.sohu.com/papp/json_interface/get_binding_status.jsp?' + Math.round(Math.random()*10000), 'get', {}, this.f_get_status_success.bind(this))
                          },
        update_folders : function(){
                           var folder_ids = document.getElementsByClassName('lock_folder');
                           var idlist = new Array();
                           for(var i = 0; i < folder_ids.length; i++){
                                   if(folder_ids[i].checked)
                                       idlist.push(folder_ids[i].getAttribute('folder_id'));
                           }
                           var param = {'folder_ids' : idlist, 'act' : 'cfolders'};
                           folder_lock(param, mailfolder.update_folder_success.bind(this));
                         },
        close_browser : function(){
                           var param = {'act' : 'logout'};
                           folder_lock(param, mailfolder.logout_success.bind(this));
                        },
        logout_success: function(ret){
                            return false;
                        }

};

var mailfolder = new MailFolder();

